package com.example.shushiyunsst.fragment.main

import android.annotation.SuppressLint
import android.app.Notification
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.Toast
import androidx.arch.core.executor.ArchTaskExecutor
import androidx.core.content.ContextCompat
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.bean.UpDataVersionBean
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.SoundPoolHelper
import com.example.library_common.utils.even.ICON_TRANSFER_NOTIFY
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.SHOW_BUYING_PAGE_CML
import com.example.library_common.utils.normalShortToast
import com.example.library_common.view.badge_view.QBadgeView
import com.example.library_common.view.bottombar.BottomBar
import com.example.library_common.view.bottombar.BottomBarTab
import com.example.library_common.view.bottombar.BottomBorInfo
import com.example.shushiyunsst.BuildConfig
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.getUserInfo
import com.example.shushiyunsst.fragment.main.home.HomeFragment
import com.example.shushiyunsst.fragment.main.home.HomePanelFragment
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.CurrencyTransferFragment
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.H5Fragment
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.FAN_BI
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.FU_KUANG
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.PushMsgBean
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.PushMsgManager
import com.example.shushiyunsst.fragment.main.mine.MineFragment
import com.example.shushiyunsst.fragment.main.mine.child.UpDataVersionPop
import com.example.shushiyunsst.fragment.main.transaction.TransactionFragment
import com.example.shushiyunsst.fragment.main.wallet.WalletFragment

import com.lxj.xpopup.XPopup
import com.umeng.message.PushAgent
import com.umeng.message.UmengMessageHandler
import com.umeng.message.entity.UMessage
import org.greenrobot.eventbus.EventBus
import kotlin.math.abs

class MainFragment : BaseFragmentEx() {
    companion object {
        fun newInstance(): MainFragment {
            val args = Bundle()

            val fragment = MainFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var childFragment = arrayOf<BaseFragmentEx>(
//        HomeFragment.newInstance(),
        HomePanelFragment.newInstance(),
        WalletFragment.newInstance(),
        TransactionFragment.newInstance(),
        CurrencyTransferFragment.newInstance(),
//        H5Fragment.newInstance(),
        MineFragment.newInstance()
    )

    private lateinit var mBottomBar: BottomBar

    private var lastBackPress = 0

    private var icon: QBadgeView? = null

    private var isLoadSubPage = false

    private var messageHandler: UmengMessageHandler = object : UmengMessageHandler() {

        override fun getNotification(p0: Context?, p1: UMessage?): Notification {

            val custom = p1?.custom
            if (!TextUtils.isEmpty(custom)) {
                showMsg(custom)
            }

            Log.d("getNotification", "getNotification: $p1")
            return super.getNotification(p0, p1)
        }


    }

    @SuppressLint("RestrictedApi")
    private fun showMsg(custom: String?) {
        ArchTaskExecutor.getMainThreadExecutor().execute {
            getUserBalanceInfo(AppGlobals.getApplication())
//            SoundUtils.getInstance().playVoice(1)
            SoundPoolHelper.play(R.raw.beep)
            try {

                val obj = JSON.parseObject(custom, PushMsgBean::class.java)

                if (obj?.type == FAN_BI || obj?.type == FU_KUANG) {
                    PushMsgManager.getInstance().addIconPushMsgList(obj)
                }

                EventBus.getDefault().post(MessageWrap.getInstance(ICON_TRANSFER_NOTIFY))

                handBag()

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

    }

    private fun handBag() {
        if (mBottomBar == null) {
            return
        }

        val tabLayout = mBottomBar.getmTabLayout()
        var index = 0
        for (e in 0 until tabLayout.childCount) {
            val bottomBarTab = tabLayout.getChildAt(e) as BottomBarTab
            if (bottomBarTab.pageTag is CurrencyTransferFragment) {
                index = e
                break
            }

        }

        val childAt = tabLayout.getChildAt(index) as BottomBarTab
        val iconPushMsgList = PushMsgManager.getInstance().iconPushMsgList
        if (iconPushMsgList.isEmpty()) {
            hidBag()
        } else {
            showBag(childAt)
        }
    }

    private fun showBag(childAt: BottomBarTab?) {

        if (icon == null) {
            icon = QBadgeView(_mActivity);
        }

        icon?.bindTarget(childAt?.icon)

            ?.setBadgeBackgroundColor(
                ContextCompat.getColor(
                    _mActivity,
                    android.R.color.holo_red_light
                )
            )
            ?.setBadgeText("")?.isShowShadow = true
    }

    private fun hidBag() {
        icon?.hide(true)
        icon = null;
    }

    override fun getLayoutId() = R.layout.main_fragment_layout

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val mPushAgent = PushAgent.getInstance(AppGlobals.getApplication())
        mPushAgent.messageHandler = messageHandler


        mBottomBar = view.findViewById(R.id.bottomBar)



        if (!isLoadSubPage) {
            loadSubPage()
            isLoadSubPage = true
        }


    }

    override fun onLazyInitView(savedInstanceState: Bundle?) {
        super.onLazyInitView(savedInstanceState)
        getUserInfo(_mActivity)
    }


    private fun loadSubPage() {
        childFragment.forEachIndexed { _, it ->
            val bottomBor = it as BottomBorInfo
            mBottomBar.addItem(
                BottomBarTab(_mActivity)
                    .setPageTag(it)
                    .setContent(bottomBor.title, bottomBor.icon)
            )
        }

        loadMultipleRootFragment(R.id.fl_container, 0, *childFragment)

        mBottomBar.setOnTabSelectedListener(object : BottomBar.OnTabSelectedListener {
            override fun onTabReselected(position: Int) {
                val nextFragment = childFragment[position]
                val mBottomBorInfo = nextFragment as BottomBorInfo

                mBottomBorInfo.refreshData()
            }

            override fun onTabUnselected(position: Int) {

            }

            override fun onTabSelected(position: Int, prePosition: Int) {
                val nextFragment = childFragment[position]

                showHideFragment(nextFragment, childFragment[prePosition])

//                val mBottomBorInfo = nextFragment as BottomBorInfo

//                mBottomBorInfo.refreshData()
            }
        })
    }


    override fun handMessage(msg: MessageWrap?) {
//        super.handMessage(msg)
        when (msg?.message) {
            ICON_TRANSFER_NOTIFY -> {
                handBag()
            }
            SHOW_BUYING_PAGE_CML -> {
                val tabLayout = mBottomBar.getmTabLayout()
                var index = -1
                for (e in 0 until tabLayout.childCount) {
                    val bottomBarTab = tabLayout.getChildAt(e) as BottomBarTab
                    if (bottomBarTab.pageTag is CurrencyTransferFragment) {
                        index = e
                        break
                    }

                }

                if (index >= 0) {
                    mBottomBar.setCurrentItem(index)
                }
            }
        }
    }

    override fun onBackPressedSupport(): Boolean {
        val currentTimeMillis = System.currentTimeMillis().toInt()
        if (abs(currentTimeMillis - lastBackPress) > 1000) {
            lastBackPress = currentTimeMillis
            normalShortToast(_mActivity, R.string.exit_app)
//            Toast.makeText(_mActivity,  , Toast.LENGTH_SHORT).show()


        } else {
            _mActivity.finish()
        }

        return true
    }
}